//
//  MineSettingViewController.m
//  AILock
//
//  Created by 谭亚明 on 2020/6/28.
//  Copyright © 2020 tym. All rights reserved.
//

#import "MineSettingViewController.h"
#import "UserTool.h"
#import "UserTool.h"
#import "ChangeLoginPasVC.h"
#import "XMPayCodeView.h"
#import "UIImageView+YPImage.h"
#import "UserModel.h"
#import "UserService.h"
#import "UIimage+Extends.h"
#import "HXPhotoManager.h"
#import "YPVideoPickerViewController.h"
#import "ChangeMobilVC.h"
#import "ChangeOpenLockPassVC.h"
#import "ChangeNicknameVC.h"
#import "ShowAlertView.h"
#import "Colors.h"
#import "UserService.h"
@interface MineSettingViewController ()<HXPhotoViewControllerDelegate>

@property(nonatomic,weak) IBOutlet UIView *conView;

@property(nonatomic,weak) IBOutlet UIImageView *headImage;
@property(nonatomic,weak) IBOutlet UILabel *naemLab;
@property(nonatomic,weak) IBOutlet UILabel *mobileLab;

@property(nonatomic,weak) IBOutlet UIButton *logOutBtn;

@property (strong, nonatomic) HXPhotoManager *manager;//相册manager

@property(nonatomic,strong) UserService *userService;
@end

@implementation MineSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    [self addTitle:@"个人设置"];
    [self initUI];
}

-(void)updateUserUI:(UserModel *)userModel{
    self.mobileLab.text = userModel.mobile;
    if (![[UserTool getLogInUser].mobile isEqualToString:userModel.mobile]) {
        [UserTool getLogInUser].mobile = userModel.mobile;
    }
    if ([userModel getEquipmentImage].length) {
        [self.headImage yp_setImageUlr:[userModel getEquipmentImage]];
        [UserTool getLogInUser].headImgUrl = userModel.headImgUrl;
    }
    if (userModel.nickname) {
        self.naemLab.text = userModel.nickname;
        [UserTool getLogInUser].nickname = userModel.nickname;
    }
}

-(void)getUpdateUser{
    TYMWeak(self);
    [self.userService getFindusercompletion:^(NSError * _Nonnull error, UserModel * _Nonnull response) {
        if (response) {
            [weakself updateUserUI:response];
        }
    }];
}

-(UserService*)userService{
    if (_userService == nil) {
        _userService = [[UserService alloc] init];
    }
    return _userService;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getUpdateUser];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
}

-(void)initUI{
    self.conView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
    self.conView.layer.cornerRadius = 4.5;
    self.conView.layer.shadowColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:0.5].CGColor;
    self.conView.layer.shadowOffset = CGSizeMake(0,0);
    self.conView.layer.shadowOpacity = 1;
    self.conView.layer.shadowRadius = 14;
    self.logOutBtn.layer.cornerRadius = 5;
    self.logOutBtn.layer.borderColor = rgba(151, 151, 151).CGColor;
    self.logOutBtn.layer.borderWidth = 1;
    self.logOutBtn.layer.masksToBounds = YES;
    self.headImage.layer.masksToBounds = YES;
    self.headImage.layer.cornerRadius = self.headImage.frame.size.height/2;

}

-(IBAction)tapHeadAction:(id)sender{
       self.manager.type  = HXPhotoManagerSelectedTypePhoto;
       self.manager.configuration.openCamera = YES;
       YPVideoPickerViewController *vc = [[YPVideoPickerViewController alloc] init];
        vc.manager = self.manager;
        vc.delegate = self;
       [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)tapNickNameAction:(id)sender{
    ChangeNicknameVC *nickName = [[ChangeNicknameVC alloc] init];
    nickName.nickNameStr = self.naemLab.text;
    [self.navigationController pushViewController:nickName animated:YES];
}

-(IBAction)tapMobileAction:(id)sender{
    ChangeMobilVC *mobilVC = [[ChangeMobilVC alloc] initWithType:0];
    [self.navigationController pushViewController:mobilVC animated:YES];
}

-(IBAction)changeLoginPasswordAction:(id)sender{
    
    ChangeLoginPasVC *changLogVC = [[ChangeLoginPasVC alloc] init];
    [self.navigationController pushViewController:changLogVC  animated:YES];
}

-(IBAction)changeUnlocking:(id)sender{
    ChangeOpenLockPassVC *changeVC = [[ChangeOpenLockPassVC alloc] init];
    [self.navigationController pushViewController:changeVC animated:YES];
}

-(IBAction)doExitAction:(id)sender{
    [ShowAlertView showAlertViewTitle:@"提示" message:@"确认退出登录吗?" actionBtnTitle:@"确定"
                           hiddenCancel:NO
                           completion:^(NSInteger actionType) {
        if(actionType){
            [self.userService getLogoutcompletion:^(NSError * _Nonnull error, LMJBaseResponse * _Nonnull response) {
                [UserTool clearUserInfocompletion:^(BOOL state) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"showLoginView" object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }];
        }
    }];
}

- (void)personalUploadHeadImgInterfaceWithImage:(UIImage *)uploadImage  {
    //网络请求管理器
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@", BaseUrl,  urlImageUpload];
    [sessionManager POST:requestUrlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@%@.jpg", [UserTool getLogInUser].token, str];
        [formData appendPartWithFileData:imageData name:@"file"  fileName:fileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (![responseObject[@"code"] integerValue]) {
            [self uploadPhone:responseObject[@"data"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WHToast showMessage:@"上传图片失败" duration:2 finishHandler:nil];
    }];
}
#pragma mark -
- (void)uploadPhone:(NSString *)photoStr{
    TYMWeak(self);
    [self.userService getUpdateUser:[UserTool getLogInUser].realName?[UserTool getLogInUser].realName:@"" sex:[UserTool getLogInUser].sex  nickName:[UserTool getLogInUser].nickname?[UserTool getLogInUser].nickname:@"" headImagUrl:photoStr completion:^(NSError * _Nonnull error, LMJBaseResponse * _Nonnull response) {
        [UserTool getLogInUser].headImgUrl = photoStr;
        [weakself.headImage yp_setImageUlr:[[UserTool getLogInUser] getEquipmentImage]];
    }];
}

#pragma mark - 懒加载选择视频的manager
- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
        _manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;
        _manager.configuration.openCamera = NO;
        _manager.configuration.videoMaxNum = 1;
        _manager.configuration.maxNum = 1;
        _manager.configuration.photoCanEdit = NO;
        _manager.configuration.hideOriginalBtn = YES;
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.replacePhotoEditViewController = NO;
        _manager.configuration.replaceVideoEditViewController = NO;
        _manager.configuration.showBottomPhotoDetail = NO;
        _manager.configuration.themeColor = [UIColor blackColor];
        _manager.configuration.navBarBackgroudColor = [UIColor blackColor];
        _manager.configuration.navigationTitleColor = [UIColor whiteColor];
        _manager.configuration.selectVideoLimitSize = YES;
        _manager.configuration.limitVideoSize = 1024*1024*100;
        _manager.configuration.photoStyle = HXPhotoStyleDark;
        _manager.configuration.cellDarkSelectBgColor = rgba(76, 132, 255);
        _manager.configuration.languageType = HXPhotoLanguageTypeSc;
        _manager.configuration.reverseDate = YES;
        _manager.configuration.videoMaximumSelectDuration = 60;
    }
    return _manager;
}

#pragma mark - HXPhotoViewController delegate
- (void)photoViewController:(HXPhotoViewController *)photoViewController
didDoneAllList:(NSArray<HXPhotoModel *> *)allList
        photos:(NSArray<HXPhotoModel *> *)photoList
        videos:(NSArray<HXPhotoModel *> *)videoList
                   original:(BOOL)original{
    if (photoList.count > 0) {
       HXPhotoModel *photoModel = photoList.firstObject;
        [self personalUploadHeadImgInterfaceWithImage:photoModel.thumbPhoto];
    }
}
@end
